package com.pinecone.controller;

import com.github.binarywang.utils.qrcode.QrcodeUtils;
import com.google.code.kaptcha.Producer;
import com.pinecone.common.exception.MinerException;
import com.pinecone.common.utils.R;
import com.pinecone.service.VerificationService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * Created by hushangjie on 2017/9/25.
 */
@RestController
@RequestMapping("api")
public class VerificationController {
    @Autowired
    private VerificationService verificationService;
    @Autowired
    private Producer producer;

    //二维码生成工具
    @GetMapping("/qr_code")
    public void getQrCode(@RequestParam(value = "url",required = true) String url,HttpServletResponse response , HttpServletRequest request){
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        try {
            url=url.replaceAll("&amp;","&");
            byte[] qRcode = QrcodeUtils.createQrcode(url,200,null);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(qRcode);
            ServletOutputStream out = null;
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            out = response.getOutputStream();
            ImageIO.write(bufferedImage, "jpg", out);
            IOUtils.closeQuietly(out);
        } catch (IOException e) {
            e.printStackTrace();
            throw new MinerException("内部错误",500);
        }

    }

    /**
     * 获取图片验证码，必须携带session
     * @param response
     * @param request
     * @throws ServletException
     * @throws IOException
     */
    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response , HttpServletRequest request){
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = verificationService.generateImgNum(request.getSession().getId());
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //获取客户端的sessionid存放至redis
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ImageIO.write(image, "jpg", out);
            IOUtils.closeQuietly(out);
        } catch (IOException e) {
            e.printStackTrace();
            throw new MinerException("内部错误",500);
        }

    }
    /**
     * 发送验证短信
     * @param phone
     * @return
     */
    @GetMapping("/send_sms_code")
    public R sendSmsCode(@RequestParam(value = "phone",required = true) String phone){
        //@Pattern(regexp = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147,145))\\\\d{8}$")
        verificationService.generateSMSNum(phone);
        return R.ok();
    }
    /**
     * 验证图片验证码，必须携带session
     * @param imgCode
     * @param request
     * @return
     */
    @GetMapping("/validate_img_code")
    public R validateImgCode(@RequestParam(value = "img_code",required = true) String imgCode,HttpServletRequest request){
        String sessionId = request.getSession().getId();
        if (sessionId != null){
            verificationService.validateImgNum(request.getSession().getId(),imgCode);
            return R.ok();
        }else {
            throw new MinerException("session不能为空");
        }


    }
    
    /**
     * 通过电话号码验证短信验证码
     * @param smsCode
     * @param phone
     * @return
     */
    @GetMapping("/validate_sms_code")
    public R validateSmsCode(@RequestParam(value = "sms_code",required = true) String smsCode,
                             @RequestParam(value = "phone",required = true) String phone){
        verificationService.validateSMSNum(phone,smsCode);
        return R.ok();
    }

}
